package com.zivwu.library.dao.net.interceptor;

import com.orhanobut.logger.Logger;

import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.Charset;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

/**
 * 用于打印请求的参数和返回的结果
 */

public class PrintInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        //获取请求的request
        Request request = chain.request();
        //在此填写request的拦截事件
        //遍历请求的formBody,打印参数
        StringBuilder builder = new StringBuilder();
        if (request.body() instanceof FormBody) {
            FormBody oldFormBody = (FormBody) request.body();
            for (int i = 0; i < oldFormBody.size(); i++) {
                builder.append(URLDecoder.decode(oldFormBody.encodedName(i))
                        + ":"
                        + URLDecoder.decode(oldFormBody.encodedValue(i)) + "%n");
            }
        }

        long t1 = System.nanoTime();
        Logger.d(String.format("Sending request %s on %s%n%s%nFormBody:%n",
                request.url(), chain.connection(), request.headers())
                + String.format(builder.toString()));

        //递归调用
        Response response = chain.proceed(request);
        //添加response拦截器
        long t2 = System.nanoTime();
        ResponseBody responseBody = response.body();
        BufferedSource source = responseBody.source();
        source.request(Long.MAX_VALUE); // Buffer the entire body.
        Buffer buffer = source.buffer();

        Charset charset = Charset.forName("UTF-8");
        MediaType contentType = responseBody.contentType();
        String s = buffer.clone().readString(charset);
//        Logger.json(response.request().url().toString(),s);
//                .json(s);
//        Logger.d(String.format("Received response for %s in %.1fms%n%s%n%s",
//                response.request().url(), (t2 - t1) / 1e6d, response.headers(),json));
        return response;
    }



}
